package cn.tedu.lucky.draw.server.service.impl;


import cn.tedu.lucky.draw.server.protocol.po.Activity;
import cn.tedu.lucky.draw.server.protocol.query.ActivityQuery;
import cn.tedu.lucky.draw.server.repository.ActivityRepository;
import cn.tedu.lucky.draw.server.service.IActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private ActivityRepository activityRepository;

    private List<Activity> activities;


    @Override
    public List<Activity> findAll(ActivityQuery activityQuery) {
        if (activities == null){
            activities = activityRepository.findAll();
        }
        String name = activityQuery.getName();
        Integer status = activityQuery.getStatus();
        return activities.stream()
                .filter(activity -> name == null || name =="" || name.equals(activity.getName()))
                .filter(activity -> status == null || status.equals(activity.getStatus()))
                .collect(Collectors.toList());
    }

    @Override
    public void save(Activity activity) {
        LocalDateTime now = LocalDateTime.now();
        activity.setCreateTime(now);
        activity.setUpdateTime(now);
        activity.setStatus(0);//待审核
        activityRepository.save(activity);
        activities = null;
    }

    @Override
    public Activity findActivityById(Long id) {
        Optional<Activity> optional = activityRepository.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }


}
